<?php
/**
 * 基础分类
 * 
 * @author kaikaic
 * @date 2018/04/09
 */

namespace app\admin\controller;

use app\travel\NodeModel;
use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;

class Category extends BasicAdmin {

    protected $table = 'SystemCategory';

    public function index() {
        $this->title = '系统分类管理';

        return parent::_list($this->table, false);
    }

    /**
     * 权限授权
     * @return string|array
     */
    public function apply() {
        $auth_id = $this->request->get('id', '0');

        switch (strtolower($this->request->get('action', '0'))) {
            case 'getnode':
                $nodes = NodeModel::get();
                $checked = Db::name('SystemAuthNode')->where('auth', $auth_id)->column('node');
                foreach ($nodes as $key => &$node) {
                    $node['checked'] = in_array($node['node'], $checked);
                    if (empty($node['is_auth']) && substr_count($node['node'], '/') > 1) {
                        unset($nodes[$key]);
                    }
                }
                $this->success('获取节点成功！', '', $this->_filterNodes($this->_filterNodes(ToolsService::arr2tree($nodes, 'node', 'pnode', '_sub_'))));
                break;
            case 'save':
                $data = [];
                $post = $this->request->post();
                foreach (isset($post['nodes']) ? $post['nodes'] : [] as $node) {
                    $data[] = ['auth' => $auth_id, 'node' => $node];
                }
                Db::name('SystemAuthNode')->where('auth', $auth_id)->delete();
                Db::name('SystemAuthNode')->insertAll($data);
                $this->success('节点授权更新成功！', '');
                break;
            default :
                $this->assign('title', '节点授权');
                return $this->_form($this->table, 'apply');
        }
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_data_filter(&$data) {
        $data = ToolsService::arr2table($data);
    }
    
    /**
     * 表单数据默认处理
     * @param array $data
     */
    public function _form_filter(&$data) {
    	if ($this->request->isPost()) {
    		$data['create_time'] = time();
    	}else {
    		$category = Db::name($this->table)->order('id desc')->select();
            $category = ToolsService::arr2table($category);
    		$this->assign('category_root', $category);
    	}
    }
    
    /**
     * 添加-分类
     */
    public function add() {
        return $this->_form($this->table, 'form');
    }

    /**
     * 编辑-分类
     */
    public function edit() {
        return $this->_form($this->table, 'form');
    }

    /**
     * 删除-分类
     */
    public function del() {
        if (DataService::update($this->table)) {
            $this->success("分类删除成功！", '');
        }
        $this->error("分类删除失败，请稍候再试！");
    }
}
